Skip to main content

Redux Toolkit

tip
  • store
    • index.js
    • features
      • vote.slice.js
  • vote.container.js
  • vote.main.js
  • vote.footer.js
store/index.js
// 导入toolkit
import { configureStore } from "@reduxjs/toolkit"
// 插件
import reduxLogger from "redux-logger"
import { thunk } from "redux-thunk"
// 导入切片
import voteReducer from "./features/vote.slice"

const store = configureStore({
reducer: {
// 按模块管理各个切片导出的reducer
vote: voteReducer
},
// 如果不指定任何中间件,默认集成redux-thunk
// 但是写了其他的,thunk要手动指定
middlewares: [reduxLogger, thunk]
})

export default store
store/features/vote.slice.js
// 切片包含reducer和action
import { createSlice } from "@reduxjs/toolkit"

const voteSlice = createSlice({
// 名称
name: "vote",
// 初始状态,自动赋值
initialState: {
supportNum: 1,
disapprovalNum: 2
},
// 业务逻辑,修改公共状态
reducers: {
// state: redux中的公共状态信息[基于immer库管理,无需自己克隆]
// action: 派发的行为对象,无需考虑action.type,取数据是:action.payload
supportAction(state, action) {
let { payload } = action
console.log("payload=", payload)

state.supportNum += 1
},
disapprovalAction(state, action) {
let { payload } = action
console.log("payload=", payload)
state.disapprovalNum += 1
}
}
})
export const { supportAction, disapprovalAction } = voteSlice.actions
export default voteSlice.reducer
vote.container.js
import React from "react"
import Main from "./vote.main"
import Footer from "./vote.footer"
import store from "./store/index"
// 1.安装react-redux
// 2.导入Provider
import { Provider } from "react-redux"
const Vote = () => {
return (
// 3.使用Provider
<Provider store={store}>
<Main />
<Footer />
</Provider>
)
}

export default Vote
vote.main.js
import React from "react"
import { useSelector } from "react-redux"

const Main = () => {
let { supportNum, disapprovalNum } = useSelector((state) => state.vote)
return (
<div>
<div>支持数:{supportNum}</div>
<div>反对数:{disapprovalNum}</div>
</div>
)
}
export default Main
vote.footer.js
import React from "react"
import { useDispatch, useSelector } from "react-redux"
import { supportAction, disapprovalAction } from "./store/features/vote.slice"

const wait = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 1000)
})
}

export default function Footer() {
// 从store上下文中获取公共状态
const { supportNum, disapprovalNum } = useSelector((state) => state.vote)
// dispatch方法
const dispatch = useDispatch()

const support = async () => {
// 派发行为对象-支持异步
// dispatch(async (dp) => {
// await wait()
// dp(supportAction("支持"))
// })
await wait()
dispatch(supportAction("支持"))
}

const disapproval = () => {
// 派发行为对象
dispatch(disapprovalAction("反对"))
}

return (
<div>
<div>总计人数:{supportNum + disapprovalNum}</div>
<button onClick={support}>支持</button>
&nbsp;
<button onClick={disapproval}>反对</button>
</div>
)
}